// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// K [author] rhyme_lph
// S [email]  rhymelph@gmail.com
// o [github] https://github.com/rhymelph

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/a.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/common/app_colors.dart';
import 'package:finance_app/src/common/app_spaces.dart';
import 'package:finance_app/src/entities/ocr_attachment_entity.dart';
import 'package:finance_app/src/entities/payment_entity.dart';
import 'package:finance_app/src/utils/cash_utils.dart';
import 'package:finance_app/src/utils/date_time_utils.dart';
import 'package:finance_app/src/utils/input_formatter_tools.dart';
import 'package:finance_app/src/utils/object_utils.dart';
import 'package:finance_app/src/widgets/button/normal_popup_button.dart';
import 'package:finance_app/src/widgets/button/normal_text_button.dart';
import 'package:finance_app/src/widgets/common_app_bar.dart';
import 'package:finance_app/src/widgets/form/attach_file_form.dart';
import 'package:finance_app/src/widgets/form/form_edit_status_inherited_widget.dart';
import 'package:finance_app/src/widgets/form/icon_currency_price_input_form.dart';
import 'package:finance_app/src/widgets/form/value_select_form.dart';
import 'package:finance_app/src/widgets/input/form_input_field.dart';
import 'package:finance_app/src/widgets/wrapper/normal_form_wrapper.dart';
import 'package:flutter/material.dart';
import 'package:finance_app/src/provider/dashboard/bank/new_account_transfer_provider.dart';
import 'package:finance_app/src/router_gen/router_meta.dart';
import 'package:tuple/tuple.dart';

@RouterMeta(paramName: "newAccountTransferPage")
class NewAccountTransferPage extends StatefulWidget {
  final PaymentEntity data;
  final bool isSelectMode;

  const NewAccountTransferPage({Key key, this.data, this.isSelectMode})
      : super(key: key);

  @override
  _NewAccountTransferPageState createState() => _NewAccountTransferPageState();
}

class _NewAccountTransferPageState extends State<NewAccountTransferPage>
    with PagePresenter<NewAccountTransferPage, NewAccountTransferProvider> {
  String get title => provider.id == null
      ? S.current.new_account_transfer
      : provider.isEdit == true
          ? S.current.edit_account_transfer
          : S.current.account_transfer;

  Widget get rightButton => listBuilder<bool>(
        selector: (_, __) => __.isEdit,
        builder: (BuildContext context, bool value, Widget child) =>
            provider.id != null && provider.isEdit == false
                ? _buildPopButton()
                : _buildSaveBtn(),
      );

  @override
  PreferredSizeWidget get appBar => getDefaultAppBar(
          titleWidget: listBuilder<bool>(
            selector: (_, __) => __.isEdit,
            builder: (BuildContext context, bool value, Widget child) =>
                Text(title),
          ),
          actions: [
            rightButton,
          ]);

  @override
  void initState() {
    provider.isSelectMode = widget.isSelectMode;
    provider.initData(widget.data);
    super.initState();
  }

  Widget _buildPopButton() => listBuilder<Tuple2<bool, List<String>>>(
        selector: (_, __) => Tuple2(
            provider.id != null && __.isEdit == true, List.from(__.menuList)),
        builder: (BuildContext context, Tuple2<bool, List<String>> value,
                Widget child) =>
            value.item1 == true
                ? Container()
                : NormalMorePopupButton(
                    onSelect: provider.onSelectMenu,
                    menuList: provider.menuList,
                  ),
      );

  Widget _buildSaveBtn() {
    return listBuilder<bool>(
      selector: (_, __) => pageStatus != PageStatus.loading,
      builder: (BuildContext context, bool value, Widget child) => value == true
          ? NormalSaveTextButton(
              onTap: provider.onSave,
            )
          : Container(),
    );
  }

  @override
  Widget wrapperBody(Widget child) {
    return listBuilder<bool>(
        selector: (_, __) => __.isEdit == true || provider.id == null,
        builder: (BuildContext context, bool value, Widget child) =>
            FormEditStatusInheritedWidget(
              isEdit: value,
              child: child,
            ),
        child: child);
  }

  @override
  Widget get buildWidget => ColoredBox(
        color: Colors.white,
        child: ListView(
          children: [
            if (widget.data?.type == 'transfer')
              Container()
            else
              listBuilder<String>(
                selector: (_, __) => __.unit?.key ?? "SGD",
                builder: (BuildContext context, String value, Widget child) =>
                    IconCurrencyPriceInputForm(
                  controller: provider.priceController,
                  focusNode: provider.priceFocusNode,
                  currency: value,
                  svgIconPath: A.assetsImagesStyleAccountTransfer,
                  onChangeCurrency: provider.onChangeUnit,
                ),
              ),
            listBuilder<DateTime>(
              selector: (_, __) => __.date,
              builder: (BuildContext context, DateTime value, Widget child) =>
                  ValueSelectForm(
                title: S.current.transaction_date,
                value: ObjectUtils.isNullDefaultFormat<DateTime>(value, null,
                    (data) => DateTimeUtils.formatGlobalDateTime(data)),
                onTap: provider.onChangeTransactionDate,
              ),
            ),
            listBuilder<String>(
              selector: (_, __) => __.fromAccount == null
                  ? null
                  : '${__.fromAccount.bankName} ${__.fromAccount.accountNumber ?? ''}(${__.fromAccount.currencyCode})',
              builder: (BuildContext context, String value, Widget child) =>
                  Stack(
                children: [
                  ValueSelectForm(
                    value: value,
                    title: provider.id == null || provider.flowType == 'out'
                        ? S.current.from
                        : S.current.to,
                    onTap: provider.onChangeFormAccount,
                  ),
                  if (value != null)
                    listBuilder<Tuple2<bool, num>>(
                        selector: (_, __) => Tuple2(
                            __.fromAccount.currencyCode == __.unit.key ||
                                !FormEditStatusInheritedWidget.ofEnable(
                                    context),
                            num.parse(
                                __.fromPriceController.text, (e) => null)),
                        builder: (BuildContext context, Tuple2<bool, num> value,
                                Widget child) =>
                            // value.item1 == true
                            //     ?
                            _buildAmount(
                              amount: value.item2,
                            )
                        // : _buildInputAmount(
                        //     amount: value.item2,
                        //     controller: provider.fromPriceController,
                        //     focusNode: provider.fromPriceFocusNode,
                        //   ),
                        ),
                ],
              ),
            ),
            listBuilder<String>(
              selector: (_, __) => __.toAccount == null
                  ? null
                  : '${__.toAccount.bankName} ${__.toAccount.accountNumber ?? ''}(${__.toAccount.currencyCode})',
              builder: (BuildContext context, String value, Widget child) =>
                  Stack(
                children: [
                  ValueSelectForm(
                    value: value,
                    title: provider.id == null || provider.flowType == 'out'
                        ? S.current.to
                        : S.current.from,
                    onTap: provider.onChangeToAccount,
                  ),
                  if (value != null)
                    listBuilder<Tuple2<bool, num>>(
                        selector: (_, __) => Tuple2(
                            __.toAccount.currencyCode == __.unit.key ||
                                !FormEditStatusInheritedWidget.ofEnable(
                                    context),
                            num.parse(__.toPriceController.text, (e) => null)),
                        builder: (BuildContext context, Tuple2<bool, num> value,
                                Widget child) =>
                            // value.item1 == true
                            //     ?
                            _buildAmount(
                              amount: value.item2,
                            )
                        // : _buildInputAmount(
                        //     amount: value.item2,
                        //     controller: provider.toPriceController,
                        //     focusNode: provider.toPriceFocusNode,
                        //   ),
                        ),
                ],
              ),
            ),
            listBuilder<String>(
              selector: (_, __) => __.transactionType?.name,
              builder: (BuildContext context, String value, Widget child) =>
                  ValueSelectForm(
                title: S.current.payment_method,
                value: value,
                onTap: provider.onChangeTransactionMethod,
              ),
            ),
            FromInputField(
              tip: S.current.cheque_transaction_numberoptional,
              controller: provider.chequeTransactionNumberController,
              focusNode: provider.chequeTransactionNumberFocusNode,
            ),
            NormalFormWrapper(
              child:
                  listBuilder<Tuple2<List<String>, List<OcrAttachmentEntity>>>(
                selector: (_, __) => Tuple2(
                    List.from(__.files), List.from(__.attachments ?? [])),
                builder: (BuildContext context,
                        Tuple2<List<String>, List<OcrAttachmentEntity>> value,
                        Widget child) =>
                    AttachFileForm(
                  onAdd: provider.onAddAttachment,
                  files: value.item1,
                  onSelectFile: provider.onSelectFile,
                  attachments: value.item2,
                  onSelectAttachment: provider.onSelectAttachment,
                ),
              ),
            ),
          ],
        ),
      );

  Widget _buildAmount({num amount}) {
    return Positioned(
        top: 0,
        bottom: 0,
        right: getDp(35),
        child: Visibility(
          visible: amount != null,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.end,
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(
                S.current.amount,
                style: TextStyle(
                  color: aceDarkGrayColor,
                  fontSize: getSp(14),
                  fontWeight: FontWeight.w400,
                  height: 1,
                ),
              ),
              AppSpaces.h10,
              Text(
                CashUtils.formatCashAmount(amount) ?? '0.00',
                style: TextStyle(
                  color: aceBlackColor,
                  fontSize: getSp(18),
                  fontWeight: FontWeight.w700,
                  height: 14 / 18,
                ),
              ),
            ],
          ),
        ));
  }
}
